
define([
    './custom/widgets/js/yufpOrgTree.js',
    './custom/plugins/YufpMgrSelector.js',
    './custom/widgets/js/yufpExtTree.js'

], function (require, exports) {
    exports.ready = function (hashCode, data, cite) {
        // 注册该功能要用到的数据字典
        yufp.lookup.reg('DATA_STS,SYS_TYPE,SEX_TYPE,SCENE_TYPE,CARD_TYPE,CUST_LEVEL,BIG_BLG_IDY,BIG_OCP_CD,BLG_IDY,OCP_CD');
        // 创建virtual model
        yufp.custom.vue({
            el: '#customerFilling',
            // 以m_开头的属性为UI数据不作为业务数据，否则为业务数据
            data: function () {
                var me = this;
                    return {
                        judgeUser:true,
                        options1:[],
                        options2:[],
                        custInfo:{
                            isDocument:'',
                            sceneType:'',
                        },
                        processApprovalInfo:{},
                        processApprovalRules:{
                            address:[
                                {required: true, message: '必填项', trigger: 'blur'}
                            ],
                            ctfNo:[
                                {required: true, message: '必填项', trigger: 'blur'}
                            ]
                        },
                        processApprovalDialogVisible:false,
                        rules: {
                            ctfTp: [
                                {required: true, message: '必填项', trigger: 'blur'}
                            ],
                            ctfNo: [
                                {required: true, message: '必填项', trigger: 'blur'}
                            ],
                            custName: [
                                {required: true, message: '必填项', trigger: 'blur'}
                            ],
                            address: [
                                {required: true, message: '必填项', trigger: 'blur'}
                            ],
                            mobNo: [
                                {required: true, validator: yufp.validator.mobile, message: "请输入正确的11位手机号", trigger: 'blur' }
                            ],
                        },
                        custData:{condition: JSON.stringify({
                                userId: yufp.session.userId,
                                orgId: yufp.session.user.org.code,
                                roleId:yufp.session.user.roles[0].code,
                                isDocument:1
                            })},
                        funcDataUrl:backend.msmFrontWebService + '/api/CustCenter/getAllCustomerInformation',
                        uploadData:{condition: JSON.stringify({
                                userId: yufp.session.userId,
                                orgId: yufp.session.user.org.code,
                            })},
                        headers: {
                            'Authorization': 'Bearer' + yufp.service.getToken()
                        },
                        importDialogVisible: false,
                        dialogFormVisible: false,
                        dialogStatus: '',
                        saveBtnShow:'',
                        formDisabled: false,
                        loading: false,
                        uploadAction: '/api/CustCenter/uploadExcel',
                };
            },
            computed: {
                action: function () {
                    var _this = this;
                    return yufp.service.getUrl({ url: _this.uploadAction });
                }
            },
            // 钩子
            created:function (){
                this.judgeUserFn()
            },
            mounted: function () {
                this.getGridName()
            },
            methods: {
                judgeUserFn:function (){
                    var me =this;
                    const roleId = yufp.session.user.roles[0].code;
                    const orgId = yufp.session.user.org.code;
                    if (roleId ==="R0008" || roleId === "R0007" || roleId === "R001"|| orgId=== "070667XN0" || orgId==="070667XN1" ||orgId==="070667860" ||orgId==="070667XN3"){
                        me.judgeUser= true;
                    }
                    else {
                        me.judgeUser= false;
                        me.getSecondGridName();
                    }
                },
                changeCustOrgId:function (){
                    this.$refs.customerInfoSearch.formdata.custGridId = '';
                    this.getSecondGridName()
                },
                getGridName:function (){
                    var me =this;
                    yufp.service.request({
                        url: backend.msmFrontWebService + '/api/CustCenter/getGridName',
                        method: 'get',
                        data: {
                            condition: JSON.stringify({
                                userId: yufp.session.userId,
                                orgId: yufp.session.user.org.code,
                                roleId:yufp.session.user.roles[0].code,
                            })
                        },
                        callback: function (code, message, response) {
                            me.options1 = response.data
                        }
                    });
                },
                getSecondGridName:function (){
                    var me =this;
                    yufp.service.request({
                        url: backend.msmFrontWebService + '/api/CustCenter/getSecondGridName',
                        method: 'get',
                        data: {
                            condition: JSON.stringify({
                                userId: yufp.session.userId,
                                orgId: yufp.session.user.org.code,
                                roleId:yufp.session.user.roles[0].code,
                                preGrid: me.judgeUser=== true ? me.$refs.customerInfoSearch.formdata.custOrgId : ''
                            })
                        },
                        callback: function (code, message, response) {
                            me.options2 = response.data
                        }
                    });
                },
                searchFn: function () {
                    var me = this;
                    var param = {
                        condition: JSON.stringify({
                            custName: me.$refs.customerInfoSearch.formdata.custName,
                            custLevel: me.$refs.customerInfoSearch.formdata.custLevel,
                            custGridId: me.$refs.customerInfoSearch.formdata.custGridId,
                            gridId: me.$refs.customerInfoSearch.formdata.custOrgId,
                            ctfNo: me.$refs.customerInfoSearch.formdata.ctfNo,
                            // custOrgId: me.$refs.customerInfoSearch.formdata.custOrgId
                        })
                    };
                    me.$refs.khtable.remoteData(param);
                },
                //查询用户是否已经存在，如果不存在就提示创建用户，如果不存在，并且查询该用户是否已经处在审批中
                processFunc:function (){
                    let _this=this;
                    let validate = false;
                    _this.$refs.processApprovalForm.validate(function (valid) {
                        validate = valid;
                    });
                    if (!validate) {
                        this.$message({message: '打*为必填项', type: 'warning'});
                        return;
                    }
                    this.loading = true;
                    yufp.service.request({
                        url: backend.msmFrontWebService + '/api/CustCenter/transferCustomer',
                        method: 'get',
                        data: {
                            condition: JSON.stringify({
                                ctfNo:_this.processApprovalInfo.ctfNo,
                                address:_this.processApprovalInfo.address,
                                sponsorNo:yufp.session.userId,
                                sponsorName:yufp.session.userName
                            })
                        },
                        callback: function (code, message, response) {
                            _this.closeProcessDialog()
                            if (response.code == 100){
                                _this.$message({message: response.message, type: 'warning'});
                            }else if (response.code == 250){
                                _this.$message({message: response.message, type: 'warning'});
                            }
                            else if(response.code == 200){
                                _this.$message({message: response.message, type: 'warning'});
                            }
                            else if(response.code == 300) {
                                _this.$message({message: response.message, type: 'success'});
                            }
                        }
                    });
                    // this.processApprovalDialogVisible=false
                },
                getCustomerInformation:function (){
                    var _this =this;
                    if (this.$refs.khtable.selections.length !== 1) {
                        this.$message({message: '请选择一个选项', type: 'warning'});
                        return;
                    }
                    _this.switchStatus('edit', true);
                    yufp.service.request({
                        url: backend.msmFrontWebService + '/api/CustCenter/getCustomerInformation',
                        method: 'get',
                        data: {
                            condition: JSON.stringify({
                                crtOprtrNo:yufp.session.userId,
                                custNo:this.$refs.khtable.selections[0].custNo
                            })
                        },
                        callback: function (code, message, response) {
                            if (code === 0) {
                                _this.custInfo.custName = response.data[0].custName;
                                _this.custInfo.isDocument = response.data[0].isDocument;
                                _this.custInfo.ctfTp = response.data[0].ctfTp;
                                _this.custInfo.ctfNo = response.data[0].ctfNo;
                                _this.custInfo.gndrCd = response.data[0].gndrCd;
                                _this.custInfo.address = response.data[0].address;
                                _this.custInfo.mobNo = response.data[0].mobNo;
                                _this.custInfo.entpIdyCgy = response.data[0].entpIdyCgy;
                                _this.custInfo.ocpCd = response.data[0].ocpCd;
                                _this.custInfo.sceneType = response.data[0].sceneType;
                                _this.custInfo.witchTypeValue = response.data[0].witchUnit.substr(0, response.data[0].witchUnit.length - 1);
                            } else {
                            }
                        }
                    });
                },
                updateImport:function (isImport,custNo){
                    var me =this;
                    yufp.service.request({
                        url: backend.msmFrontWebService + '/api/CustCenter/updateCustomerImport',
                        method: 'get',
                        data: {
                            condition: JSON.stringify({
                                isImport:isImport,
                                crtOprtrNo:yufp.session.userId,
                                custNo:custNo
                            })
                        },
                        callback: function (code, message, response) {
                            me.restInputValue();
                            me.$refs.khtable.remoteData();
                            if (code === 0) {
                                if (isImport === "0"){
                                    me.$message({message: '添加重点客户成功', type: 'success'});
                                }
                                if(isImport === "1"){
                                    me.$message({message: '取消重点客户成功', type: 'success'});
                                }
                                //获取上级网格名称和ID
                            } else {
                                me.$message({message: '重点客户变更失败', type: 'warning'});
                            }
                        }
                    });},
                deleteCustomer:function (){
                    var _this = this;
                    //删除时的选项校验
                    if (_this.$refs.khtable.selections.length === 0) {
                        _this.$message({message: '请选择至少一个选项', type: 'warning'});
                        return;
                    }
                    var custNoArray =[];
                    for (var i=0;i<_this.$refs.khtable.selections.length;i++){
                        custNoArray.push(_this.$refs.khtable.selections[i].custNo)
                    }
                    yufp.service.request({
                        url: backend.msmFrontWebService + '/api/CustCenter/deleteCustomer',
                        method: 'get',
                        data: {
                            condition: JSON.stringify({
                                userId: yufp.session.userId,
                                orgId: yufp.session.user.org.code,
                                custNo:custNoArray,
                            })
                        },
                        callback: function (code, message, response) {
                            _this.$refs.khtable.remoteData();
                            if (response !== 0) {
                                _this.$message({message: '删除成功', type: 'success'});
                                //获取上级网格名称和ID
                            } else {
                                console.info("失败");
                            }
                        }
                    });
                },
                addCustFn:function (){
                    var _this = this;
                    _this.restInputValue();
                    _this.switchStatus('add', true);
                },
                //显示导入窗口
                importFn: function () {
                    this.importDialogVisible = true;
                },
                openProcessApprovalFn: function () {
                    this.processApprovalDialogVisible = true;
                },
                saveEditFunc: function () {
                    let _this=this;
                    let validate = false;
                    _this.$refs.custForm.validate(function (valid) {
                        validate = valid;
                    });
                    if (!validate) {
                        this.$message({message: '打*为必填项', type: 'warning'});
                        return;
                    }
                    yufp.service.request({
                        url: _this.dialogStatus ==='edit' ? backend.msmFrontWebService + '/api/CustCenter/updateCustomerInformation' : backend.msmFrontWebService + '/api/CustCenter/addNewCustomer',
                        method: 'get',
                        data: {
                            condition: JSON.stringify({
                                custNo:_this.dialogStatus ==='edit' ? _this.$refs.khtable.selections[0].custNo :'',
                                custName:_this.custInfo.custName,
                                crtOprtrNo:yufp.session.userId,
                                crtBrchNo:yufp.session.user.org.code,
                                ctfTp:_this.custInfo.ctfTp,
                                ctfNo:_this.custInfo.ctfNo,
                                gndrCd:_this.custInfo.gndrCd,
                                address:_this.custInfo.address,
                                mobNo:_this.custInfo.mobNo,
                                entpIdyCgy:_this.custInfo.entpIdyCgy,
                                ocpCd:_this.custInfo.ocpCd,
                                sceneType:_this.custInfo.sceneType,
                                witchUnit:_this.custInfo.witchTypeValue + (_this.custInfo.sceneType === '1' ? '组':_this.custInfo.sceneType === '0' ? '栋' :''),
                            })
                        },
                        callback: function (code, message, response) {
                            _this.restInputValue();
                            if(_this.dialogStatus === 'edit' && code ===0){
                                    _this.$refs.khtable.remoteData();
                                    _this.$message({message: '更新客户成功', type: 'success'});
                            }
                            else if (_this.dialogStatus === 'add' && response.data === 1) {
                                let integralCode = '10';
                                yufp.util.addIntegral(integralCode)
                                _this.$refs.khtable.remoteData();
                                _this.$message({message: '新增客户成功', type: 'success'});
                            } else {
                                _this.$message({message: '新增客户失败,请检查是否插入了重复的客户', type: 'warning'});
                            }
                        }
                    });
                },
                //每次执行显示操作，新增操作执行清空，修改执行查询，
                restInputValue:function (){
                    var _this = this;
                    _this.dialogFormVisible = false;
                    _this.$nextTick(function () {
                        if (_this.$refs.custForm){
                            _this.$refs.custForm.resetFields();
                        }
                    });
                },
                //文件上传成功回调
                onSuccess: function (response, file, fileList) {
                    var _this = this;
                    var res = response;
                    window.console.info(response.code);
                    if (response.code == 200) {
                        _this.$refs.khtable.remoteData();
                        _this.$message({
                            message: '上传文件成功',
                            type: 'success'
                        });
                    } else {
                        _this.$message({
                            message: res.message,
                            type: 'error'
                        });
                    }
                    _this.loading = false;
                    this.importDialogVisible = false;
                    _this.$refs.upload.clearFiles();
                },
                //上传失败回调
                onError: function (err, file, fileList) {
                    window.console.log(err);
                    this.loading = false;
                },
                //关闭上传弹窗
                closeDialog: function () {
                    this.$refs.upload.clearFiles();
                    this.loading = false;
                    this.importDialogVisible = false;
                },
                //关闭移交客户弹窗
                closeProcessDialog: function () {
                    var _this =this;
                    this.loading = false;
                    this.processApprovalDialogVisible = false;
                    _this.$nextTick(function () {
                        if (_this.$refs.processApprovalForm){
                            _this.$refs.processApprovalForm.resetFields();
                        }
                    });
                },
                submitUpload: function () {
                    var _this = this;
                    _this.loading = true;
                    if(_this.$refs.upload.uploadFiles.length ===0){
                        _this.$message({ message: '请上传文件再进行操作' });
                        _this.loading=false;
                        return;
                    }
                    var fileName = _this.$refs.upload.uploadFiles[0].name;
                    if (fileName.lastIndexOf('.') != -1) {
                        var fileType = (fileName.substring(fileName.lastIndexOf('.') + 1, fileName.length)).toLowerCase();
                        var supportFile = [];
                        supportFile[0] = 'xls';
                        supportFile[1] = 'xlsx';
                        if ($.inArray(fileType, supportFile) < 0) {
                            _this.$message({ message: '不支持的文件类型' });
                            _this.loading=false;
                            return;
                        }
                    } else {
                        _this.$message({ message: '文件只支持xls,xlsx' });
                        _this.loading=false;
                        return;
                    }
                    this.$refs.upload.submit();
                },
                lookupInformation:function (){
                    // console.log(this.$refs.khtable.selections)
                    var _this =this;
                    if (this.$refs.khtable.selections.length !== 1) {
                        this.$message({message: '请选择一个选项', type: 'warning'});
                        return;
                    }
                    _this.restInputValue();
                    _this.switchStatus('detail', false);
                    yufp.service.request({
                        url: backend.msmFrontWebService + '/api/CustCenter/getCustomerInformation',
                        method: 'get',
                        data: {
                            condition: JSON.stringify({
                                crtOprtrNo:yufp.session.userId,
                                custNo:this.$refs.khtable.selections[0].custNo
                            })
                        },
                        callback: function (code, message, response) {
                            if (code === 0) {
                                _this.custInfo.custName = response.data[0].custName;
                                _this.custInfo.isDocument = response.data[0].isDocument;
                                _this.custInfo.ctfTp = response.data[0].ctfTp;
                                _this.custInfo.ctfNo = response.data[0].ctfNo;
                                _this.custInfo.gndrCd = response.data[0].gndrCd;
                                _this.custInfo.address = response.data[0].address;
                                _this.custInfo.mobNo = response.data[0].mobNo;
                                _this.custInfo.entpIdyCgy = response.data[0].entpIdyCgy;
                                _this.custInfo.ocpCd = response.data[0].ocpCd;
                                _this.custInfo.sceneType = response.data[0].sceneType;
                                _this.custInfo.witchTypeValue = response.data[0].witchUnit ? response.data[0].witchUnit.substr(0, response.data[0].witchUnit.length - 1) : null;
                            } else {
                            }
                        }
                    });
                },
                switchStatus: function (viewType, editable) {
                    var _this = this;
                    _this.dialogStatus = viewType;
                    _this.saveBtnShow = editable;
                    _this.dialogFormVisible = true;
                    _this.formDisabled = !editable;
                },
				//客户视图
				toCustView: function (scope) {
				  var _this = this;
				  var selectedCustInfo = null;
				  if (scope == undefined && scope == null) {
				    _this.$message({ message: '客户信息错误!', type: 'warning' });
				    return;
				  }else{
				    selectedCustInfo = scope;
				  }
				  var custInfo = {'custNo': selectedCustInfo.custNo,
				    'custName': selectedCustInfo.custName
				  };
				  // 生成tab页签及路由ID
				  var customKey = 'custom_view' + selectedCustInfo.custNo; // 请以custom_view前缀开头，并且全局唯一
				  var routeId = 'custView' + selectedCustInfo.custNo; // 路由ID，设置唯一，以便消息传递，并且不允许修改，客户视图内的页面间通信会用到
				  // 传递的业务数据
				  var popageData = {
				    id: '123', // 视图树节点id
				    cust: custInfo
				  };
				  var toPageurl = 'pages/example/custView/custView';
				  var r = yufp.router.getRoute(routeId);
				  var t = new Date().getTime();
				  if (!r || !r.html) {
				    yufp.router.addRoute(routeId, {
				      html: toPageurl+'.html',
				      js: toPageurl+'.js'
				    });
				  }
				  yufp.frame.addTab({
				    id: routeId, // 菜单功能ID（路由ID）
				    key: customKey, // 自定义唯一页签key,请统一使用custom_前缀开头
				    title: '客户:' + selectedCustInfo.custName, // 页签名称
				    data: popageData // 传递的业务数据，可选配置
				  });
				}
            }
        });
    };

    // 消息处理
    exports.onmessage = function (type, message) { };

    // page销毁时触发destroy方法
    exports.destroy = function (id, cite) {};
});
